<template>
  <div class="app-container">
    <el-tabs v-model="activeName" @tab-click="handleClick">
      <el-tab-pane label="地图模式" name="first">
        <div class="titleHandle">
          <div>
            <span>{{ $t("area.LayerName") }}</span>
            <treeselect
              v-model="mapValue"
              :placeholder="$t('area.chosenLayer')"
              :max-height="300"
              :options="mapList"
              @input="handleMapChange"
            />
          </div>
          <span>{{ $t("operating.operating") }}</span>
          <el-tooltip
            v-for="(item, index) in $t('camera.drawForms')"
            :key="index"
            effect="dark"
            :content="item.label"
            placement="bottom"
          >
            <el-button
              :key="item.value"
              type="text"
              :autofocus="false"
              :data-id="item.value"
              :label="item.label"
              size="mini"
              @click="handleChange(index, item.value)"
            >
              <i
                :class="[
                  item.id == colorFlag ? item.unIconFont : item.iconFont,
                ]"
              />
            </el-button>
          </el-tooltip>
          <div>
            <el-button v-show="show2" @click="deleteForm">{{
              $t("operating.delete")
            }}</el-button>
          </div>
        </div>
        <div>
          <div id="mapbox">
            <!-- 地图容器 -->
            <div
              id="map"
              :style="{ height: mapHeight, width: mapWidth }"
            />
            <div class="positiondiv"><span /></div>
            <div class="scalediv"><span /></div>
          </div>
        </div>
      </el-tab-pane>
      <el-tab-pane label="表格模式" name="second">
        <div>
          <el-table :data="tableData" style="width: 100%" :height="tableHeight">
            <!--多选框-->
            <!--<el-table-column type="selection" width="50" align="center"></el-table-column>-->
            <el-table-column
              prop="layerName"
              :label="$t('area.LayerName')"
              min-width="120"
            />
            <el-table-column
              prop="cameraName"
              :label="$t('camera.cameraName')"
              min-width="120"
            />
            <el-table-column
              prop="cameraIp"
              :label="$t('camera.cameraIp')"
              min-width="120"
            />
            <!--<el-table-column prop="port" label="端口号" width="120"></el-table-column>-->
            <el-table-column
              prop="cameraUser"
              :label="$t('camera.cameraUser')"
              min-width="120"
            />
            <el-table-column
              prop="cameraPwd"
              :label="$t('camera.cameraPwd')"
              min-width="120"
            />
            <el-table-column
              prop="cameraVendor"
              :label="$t('camera.cameraVendor')"
              :formatter="stateFormat"
              min-width="120"
            />
            <el-table-column
              prop="cameraPort"
              :label="$t('camera.cameraPort')"
              min-width="120"
            />
            <el-table-column
              prop="cameraPosition"
              :formatter="cameraPosition"
              :label="$t('camera.cameraPosition')"
              min-width="120"
            />
            <!--操作-->
            <el-table-column :label="$t('operating.operating')" min-width="180">
              <template slot-scope="scope">
                <!--<el-button size="mini" @click="handlePreview(scope.$index, scope.row)">预览</el-button>-->
                <el-button
                  size="mini"
                  type="primary"
                  @click="handleEdit(scope.$index, scope.row)"
                >
                  {{ $t("operating.handle") }}
                </el-button>
                <el-button
                  size="mini"
                  type="primary"
                  @click="testPhoto(scope.$index, scope.row)"
                >{{ $t("realtime.testPhoto") }}</el-button>
                <el-button
                  size="mini"
                  type="danger"
                  @click="handleDelete(scope.$index, scope.row)"
                >
                  {{ $t("operating.delete") }}
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="pagination">
            <el-pagination
              background
              :current-page="currentPage"
              :page-sizes="[10, 25, 50, 100]"
              layout="total, sizes, prev, pager, next, jumper"
              :total="this.total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </div>
      </el-tab-pane>
    </el-tabs>

    <div
      :style="{ height: mapHeight }"
      style="position: relative; margin: 0 15px 0 15px; background-color: #fff"
    >
      <!--新增和编辑-->
      <el-dialog
        :title="$t('operating.add')"
        :visible.sync="editVisible"
        width="30%"
        @close="closeDialog"
      >
        <el-form ref="form" label-width="120px">
          <!--摄像头名字-->
          <el-form-item :label="$t('camera.cameraName')">
            <el-input v-model="form.cameraName" style="width: 215px" />
          </el-form-item>
          <!--IP地址-->
          <el-form-item :label="$t('camera.cameraIp')">
            <el-input v-model="form.cameraIp" style="width: 215px" />
          </el-form-item>

          <!--端口-->
          <!-- <el-form-item :label="$t('camera.cameraPort')"
                        v-if="show5">
            <el-input v-model="form.cameraPort"
                      style="width: 215px;"></el-input>
          </el-form-item> -->
          <el-form-item v-if="true" :label="$t('camera.cameraPort')">
            <el-input v-model="form.cameraPort" style="width: 215px" />
          </el-form-item>

          <!--用户名-->
          <el-form-item :label="$t('camera.cameraUser')">
            <el-input v-model="form.cameraUser" style="width: 215px" />
          </el-form-item>
          <!--密码-->
          <el-form-item :label="$t('camera.cameraPwd')">
            <el-input v-model="form.cameraPwd" style="width: 215px" />
          </el-form-item>
          <!--摄像头品牌-->
          <el-form-item :label="$t('camera.cameraVendor')">
            <!-- <el-input v-model="form.cameraVendor" style="width: 215px;"></el-input> -->
            <el-select
              v-model="form.cameraVendor"
              placeholder="请选择"
              style="width: 215px"
            >
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <!--监控数据类型-->
          <!-- <el-form-item :label="$t('camera.cameraSourceType')">
            <el-select v-model="form.sourceType"
                       filterable
                       :placeholder="$t('operating.pleaseChosen')"
                       style="width: 215px;"
                       @change="sourceTypeChange">
              <el-option v-for="item in sourceTypeList"
                         :key="item.value"
                         :label="item.label"
                         :value="item.value"></el-option>
            </el-select>
          </el-form-item> -->

          <!--摄像头监控区域-->
          <el-form-item :label="$t('camera.cameraFenceList')">
            <el-select
              v-model="fenceIdx"
              filterable
              :placeholder="$t('operating.pleaseChosen')"
              style="width: 215px"
            >
              <el-option
                v-for="item in cameraFenceList"
                :key="item.idx"
                :label="item.fenceName"
                :value="item.idx"
              />
            </el-select>
          </el-form-item>
        </el-form>
        <!--操作-->
        <span slot="footer" class="dialog-footer">
          <el-button type="primary" @click="saveEdit">{{
            $t("operating.determine")
          }}</el-button>
          <el-button @click="closeDialog">{{
            $t("operating.cancel")
          }}</el-button>
        </span>
      </el-dialog>

      <!--删除提示框-->
      <el-dialog
        :title="$t('operating.prompt')"
        :close-on-click-modal="false"
        :visible.sync="delVisible"
        width=""
      >
        <div class="del-dialog-cnt">{{ $t("operating.deletePrompt") }}</div>
        <span slot="footer" class="dialog-footer">
          <el-button type="primary" @click="deleteRow">{{
            $t("operating.determine")
          }}</el-button>
          <el-button @click="delVisible = false">{{
            $t("operating.cancel")
          }}</el-button>
        </span>
      </el-dialog>

      <!--删除围栏提示框-->
      <el-dialog
        :title="$t('operating.prompt')"
        :close-on-click-modal="false"
        :visible.sync="delFenceVisible"
        width=""
      >
        <div class="del-dialog-cnt">{{ $t("operating.deletePrompt") }}</div>
        <span slot="footer" class="dialog-footer">
          <el-button type="primary" @click="deleteFence">{{
            $t("operating.determine")
          }}</el-button>
          <el-button @click="delFenceVisible = false">{{
            $t("operating.cancel")
          }}</el-button>
        </span>
      </el-dialog>
    </div>

    <!-- 摄像头拍照是否显示 -->
    <el-dialog :visible.sync="show8">
      <img :src="imageURl" alt="" height="400">
    </el-dialog>
  </div>
</template>
<script>
import { GeoJSON } from 'ol/format.js'
import { Draw, Modify, Snap, Select, Translate } from 'ol/interaction.js'
import { Circle, LineString, Point, Polygon } from 'ol/geom.js'
import { createRegularPolygon, createBox } from 'ol/interaction/Draw.js'
import { getMapTree, getMap, cameraOne, getSingleCameraPhoto, fenceList, addFence, addCamera, cemeraList, delCamera, delCameraInfo } from '@/api/cy.js'
import {
  Load_Map,
  Load_Fence,
  _iMap,
  FenceSource,
  FenceStyle,
  _createTooltip,
  _createMeasureTooltip,
  _TransMetric,
  Tooltip,
  TooltipElement,
  _dPR,
  measureTooltipElement,
  measureTooltip,
  Load_Camera,
  CameraSource,
  releaseFence,
  LoadTypeData,
  sendThis
} from '@/utils/iMap.js'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import { baseUrl } from '@/utils/global.js'
export default {
  components: { Treeselect },
  data() {
    return {
      activeName: 'first',
      tableDataUrl: '',
      deptValue: '',
      color2: null, // ColorPicker 颜色选择器,无默认值；
      oldMapId: '',
      tableData: [],
      mapList: [],
      deptList: [],
      fenceList: [],
      cameraFenceList: [],
      mapValue: null, // 选择的地图
      text: this.$t('operating.tabularMode'),
      currentPage: 1, // 当前所在页
      total: 0, // 总页数
      pageSize: '10', //
      show: '1', // 切换显示的页面

      mapHeight: window.innerHeight - 130 + 'px', // 地图区域高度
      mapWidth: window.innerWidth + 'px',
      delcameraId: [],

      show1: true,
      show2: false,
      show3: false,
      show4: false,
      show5: true, // 端口是否显示
      show6: true,
      drawFormValue: 'None', // 绘制形状
      colorFlag: 0,
      drawForms: [
        {
          id: 0,
          value: 'None',
          label: '无操作',
          iconFont: 'al-icon-carxuanzegongju1',
          unIconFont: 'al-icon-carxuanzegongju'
        },
        {
          id: 1,
          value: 'Point',
          label: '添加摄像头',
          iconFont: 'al-icon-carshexiangtou',
          unIconFont: 'al-icon-carshexiangtou1'
        },
        {
          id: 2,
          value: 'Select',
          label: '修改摄像头',
          iconFont: 'al-icon-carbianji-kong',
          unIconFont: 'al-icon-carbianji-shi'
        }
      ],

      /** *******************表格相关*********************/
      tableHeight: window.innerHeight - 260,
      editVisible: false, // 编辑框是否可见
      delVisible: false, // 删除框是否可见
      editEnable: true, // 点击的编辑or添加
      delFenceVisible: false,
      // 用户表单提交
      form: { dept: '', sourceType: 'RTSP' },
      sourceTypeList: [
        { value: 'RTSP', label: 'RTSP' },
        { value: 'ONVIF', label: 'ONVIF' }
      ],
      _drawForm: null, // 保存当前绘制的形状
      _snap: null,
      _modify: null,
      _select: null,
      _translate: null,
      _tempval: '',
      _selectFeatureId: '',
      _selectFeatureName: '',

      //* ****点
      Point: null,
      //* ****线
      LineString: null,
      //* ****矩形
      Box: null,
      //* ****方块
      Square: null,
      //* ****圆形
      Circle: null,
      //* ****多边形
      Polygon: null,
      selectPointerMove: null,
      fenceIdx: null,
      options: [
        { label: '海康威视', value: '0' },
        { label: '大华', value: '1' },
        { label: '华为', value: '2' },
        { label: 'TP-LINK', value: '3' }
      ],
      show8: false, // 显示摄像头拍照框是否显示
      imageURl: null // 显示摄像头拍照的照片路径
    }
  }, // 注册组件
  mounted() {
    // 动态设置map的高度
    // 首先在DOM渲染数据时，设置map的高度
    this.windowRefresh()
    // 然后监听window的resize事件，在浏览器窗口变化时再设置下map的高度
    // console.log("onresize:");
    const self = this
    window.onresize = function temp() {
      self.windowRefresh()
    }

    this.init()
  },
  methods: {
    handleClick(tab, event) {
      console.log(tab, event)
    },

    // 刷新窗口
    windowRefresh: function() {
      // let h = document.documentElement.mapHeight - 160;
      this.tableHeight = window.innerHeight - 250
      this.mapHeight = window.innerHeight - 130 + 'px'
      this.mapWidth = window.innerWidth + 'px'
      // this.mapWidth = window.innerWidth + "px";
    },

    sourceTypeChange(val) {
      if (val === 'ONVIF') {
        this.show5 = true
      } else {
        this.show5 = false
      }
    },

    // 位置格式
    cameraPosition(row, column) {
      return '[' + row.posX + ',' + row.posY + ']'
    },
    // 页面显示模式
    isShowStyle() {
      if (this.show == 1) {
        // console.log(this.text);
        this.text = this.$t('operating.mapMode')
        this.show = 2
        this.show6 = false
      } else if (this.show == 2) {
        this.text = this.$t('operating.tabularMode')
        this.show = 1
        this.show6 = true
      }
    },
    // 是否显示面板
    showPanel() {
      this.show1 = !this.show1
      if (this.show1) {
        this.$refs.showPanel.style.right = '0px'
        this.$refs.iClass.className = 'el-icon-d-arrow-right'
      } else {
        this.$refs.showPanel.style.right = '-270px'
        this.$refs.iClass.className = 'el-icon-d-arrow-left'
      }
    },
    // 重置表格显示格式
    // 所有围栏列表
    fenceListSave(row, column) {
      const fenceArr = []
      if (row.fenceList) {
        for (let j = 0; j < row.fenceList.length; j++) {
          fenceArr.push(row.fenceList[j].fenceName)
        }
        return fenceArr.join('，')
      }
    },
    // 初始化默认地图
    initMap() {
      Load_Map(
        this.$store.state.initPicPath,
        67.65,
        54.16,
        1600,
        1280,
        1600 / 67.65,
        [-60, -30]
      )
      sendThis(this)
      LoadTypeData()
    },
    // 初始化函数
    init: function() {
      // 加载地图树
      getMapTree().then((res) => {
        const RES = this.responseUse(res)
        this.mapList = RES
      })
      // 初始化地图
      this.initMap()
      this.fenceDraw_init()

      this.getData()
    },
    // 切换图层
    handleMapChange() {
      // this.v_MyMessage("选择的树分支ID：" + this.mapValue, "success");
      if (this.mapValue == '') {
        this.v_MyMessage(this.$t('Notice.mapIDIsEmpty'), 'warning')
        return false
      } else {
        if (this.oldMapId != this.mapValue) {
          getMap(this.mapValue).then((res) => {
            const RES = this.responseUse(res)
            this.mapName = RES.mapName
            Load_Map(
              baseUrl + RES.mapPath,
              RES.mapActualX,
              RES.mapActualY,
              RES.mapPixelX,
              RES.mapPixelY,
              RES.mapPixelX / RES.mapActualX,
              [RES.mapOriginX, RES.mapOriginY]
            )
            this.getFenceByAreaId('camera', this.mapValue)
            this.Geo =
              baseUrl +
              '/fenceInfo/findListByFenceTypeGeoJson?fenceType=camera&layerId=' +
              this.mapValue
            releaseFence()
            Load_Fence(this.Geo)
            this.cameraGeo =
              baseUrl +
              '/cameraConfig/findCameraGeoJson?layerId=' +
              this.mapValue
            Load_Camera(this.cameraGeo)
            this.fenceSelect()

            if (this.drawFormValue != 'None' && this.drawFormValue != '') {
              this.handleChange(this.colorFlag, this.drawFormValue)
            }
          })
        }
      }
    },
    /*
     * 操作切换
     * */
    handleChange(val, type) {
      if (!this.mapValue) {
        this.v_MyMessage(this.$t('Notice.mapIDIsEmpty'), 'warning')
        return
      } else {
        this.colorFlag = val
        if (type == 'None') {
          this.show2 = false
          if (this.selectPointerMove != null) {
            _iMap.removeInteraction(this.selectPointerMove)
            this.fenceSelect()
          }
          this.fenceDraw_Destroy()
          this.fenceModify_Destroy()
        } else if (type == 'Select') {
          this.show2 = true
          // this.fenceDraw_Destroy();
          // this.fenceModify_init();
          // this.fenceModify_setActive(true);
        } else {
          this.show2 = false
          if (this.selectPointerMove != null) {
            _iMap.removeInteraction(this.selectPointerMove)
            this.fenceSelect()
          }
          this.fenceModify_Destroy()
          this.fenceDraw_changeInteraction(type)
          this.fenceDraw_setActive(true, type)
        }
      }
    },
    //  选择摄像头
    fenceSelect() {
      const self = this
      const obj = {}
      self.selectPointerMove = new Select()
      _iMap.addInteraction(self.selectPointerMove)
      self.selectPointerMove.on('select', function(e) {
        if (e.selected.length > 0) {
          // 鼠标移入，选择了一个，大概是mouseover事件

          if (e.selected[0].get('type') == 'Camera') {
            console.log(e.selected[0])
            self.editEnable = false
            self.cameraId = e.selected[0].get('idx')
            self.mapValue = e.selected[0].get('layerId')
            cameraOne(e.selected[0].get('idx'))
              .then((res) => {
                const RES = self.responseUse(res)
                // 设置编辑框为可见状态
                self.editVisible = true
                // self.form['cameraIp'] = RES.cameraIp;
                // self.form['cameraName'] = RES.cameraName;
                // self.form['cameraPwd'] = RES.cameraPwd;
                // self.form['cameraUser'] = RES.cameraUser;
                // self.form['cameraVendor'] = RES.cameraVendor;
                // self.form['sourceType'] = RES.sourceType;
                // self.form['cameraPort'] = RES.cameraPort;
                obj.cameraIp = RES.cameraIp
                obj.cameraName = RES.cameraName
                obj.cameraPwd = RES.cameraPwd
                obj.cameraUser = RES.cameraUser
                obj.cameraVendor = RES.cameraVendor
                obj.cameraPort = RES.cameraPort
                if (RES.fenceId) {
                  self.fenceIdx = Number(RES.fenceId)
                } else {
                  self.fenceIdx = null
                }
                self.posX = RES.posX
                self.posY = RES.posY
                self.form = obj
              })
          }
        }
      })
    },
    // 分页导航
    handleSizeChange(val) {
      this.pageSize = val
      this.getData()
    },
    handleCurrentChange(val) {
      this.currentPage = val
      this.getData()
    },
    deleteForm() {
      const sel = this.fenceModify_getSelectFeatures()
      // console.log(sel);
      if (sel.array_.length > 0) {
        this.fenceModify_Delete()
      } else {
        this.v_MyMessage(this.$t('Notice.cameraNotSelected'), 'warning')
      }
    },

    // 确定添加摄像头
    saveEdit() {
      let param = {}
      if (this.editEnable) {
        param = {
          cameraIp: this.form.cameraIp,
          cameraName: this.form.cameraName,
          cameraUser: this.form.cameraUser,
          cameraPwd: this.form.cameraPwd,
          cameraVendor: this.form.cameraVendor,
          sourceType: 'RTSP',
          cameraPort: this.form.cameraPort,
          posX: eval(this.coors)[0],
          posY: eval(this.coors)[1],
          // "enable":"1",
          fenceId: this.fenceIdx,
          layerId: this.mapValue
        }
      } else {
        param = {
          cameraIp: this.form.cameraIp,
          cameraName: this.form.cameraName,
          cameraUser: this.form.cameraUser,
          cameraPwd: this.form.cameraPwd,
          cameraVendor: this.form.cameraVendor,
          sourceType: 'RTSP',
          cameraPort: this.form.cameraPort,
          posX: this.posX,
          posY: this.posY,
          // "enable":"1",
          fenceId: this.fenceIdx,
          layerId: this.mapValue,
          idx: this.cameraId
        }
      }
      console.log(param)
      this.$api.cameramanage.addCamera(param).then((res) => {
        const RES = this.responseUse(res, true)
        if (RES) {
          this.editVisible = false
          Load_Camera(this.cameraGeo)
          this.getData()
          this.form = {}
        }
      })
    },
    // 行编辑按钮响应
    handleEdit(index, row) {
      // this.show = 1;
      // this.text = "地图模式";
      this.selectIndex = index
      // this.form = {};
      const obj = {}

      this.editEnable = false
      this.cameraId = row.idx
      this.$api.cameramanage.cameraOne(row.idx).then((res) => {
        if (row.layerId) {
          this.mapValue = row.layerId
          this.getFenceByAreaId('camera', row.layerId)
        }
        const RES = this.responseUse(res)
        // 设置编辑框为可见状态
        this.editVisible = true
        obj.cameraIp = RES.cameraIp
        obj.cameraName = RES.cameraName
        obj.cameraPwd = RES.cameraPwd
        obj.cameraUser = RES.cameraUser
        obj.cameraVendor = RES.cameraVendor
        obj.cameraPort = RES.cameraPort

        if (RES.fenceId) {
          this.fenceIdx = Number(RES.fenceId)
        } else {
          this.fenceIdx = null
        }
        this.posX = RES.posX
        this.posY = RES.posY
        this.form = obj
      })
    },
    // 行删除按钮响应
    handleDelete(index, row) {
      this.selectIndex = index
      // 设置删除提示框为可见状态
      this.delVisible = true
      this.delcameraId.push({ idx: row.idx })
    },
    //  确定删除
    deleteRow() {
      delCameraInfo(this.delcameraId).then((res) => {
        const RES = this.responseUse(res, true)
        if (RES) {
          this.delVisible = false
          this.getData()
          Load_Camera(this.cameraGeo)
        }
      })
    },
    closeDialog() {
      this.show5 = false

      if (this.selectPointerMove != null) {
        _iMap.removeInteraction(this.selectPointerMove)
        this.editVisible = false
        this.fenceSelect()
      } else {
        this.editVisible = false
        this.editEnable = true
      }
    },
    // 获取表格数据
    getData() {
      const param = {
        pageNum: this.currentPage,
        pageSize: this.pageSize,
        columnFilters: { fenceType: { name: 'fenceType', value: 'alarm' }}
      }
      cemeraList(param).then((res) => {
        const RES = this.responseUse(res)
        this.total = RES.totalSize
        this.tableData = RES.content
      })
    },
    // 获取当前图层所有的围栏列表
    getFenceByAreaId(type, data) {
      fenceList(type, data).then((res) => {
        const RES = this.responseUse(res)
        this.cameraFenceList = RES
      })
    },
    // 确定删除围栏
    deleteFence() {
      const param = {
        idx: this.idx
      }
      delCamera([param]).then((res) => {
        const RES = this.responseUse(res, true)
        if (RES) {
          FenceSource.removeFeature(this.selectFeature)
        }
        this.delFenceVisible = false
      })
    },
    fenceDraw_init: function() {
      //* ****点
      this.Point = new Draw({ source: CameraSource, type: 'Point' })
      //* ****线
      this.LineString = new Draw({ source: FenceSource, type: 'LineString' })
      //* ****矩形
      this.Box = new Draw({
        source: FenceSource,
        type: 'Circle',
        geometryFunction: createBox()
      })
      //* ****方块
      this.Square = new Draw({
        source: FenceSource,
        type: 'Circle',
        geometryFunction: createRegularPolygon(4)
      })
      //* ****圆形
      this.Circle = new Draw({ source: FenceSource, type: 'Circle' })
      //* ****多边形
      this.Polygon = new Draw({ source: FenceSource, type: 'Polygon' })

      /**
       * 创建工具栏tooltip
       */
      _createTooltip(true)
      _createMeasureTooltip()
    },

    fenceDraw_changeInteraction: function(type) {
      // 切换之前先移除，如果是第一操作，则不进行移除
      if (this._drawForm != null) {
        _iMap.removeInteraction(this._snap)
        _iMap.removeInteraction(this._drawForm)
      }
      this._tempval = type
      // (type);
      if (type === 'Point') {
        this._drawForm = this.Point
      } else if (type === 'Square') {
        this._drawForm = this.Square
      } else if (type === 'Circle') {
        this._drawForm = this.Circle
      } else if (type === 'Polygon') {
        this._drawForm = this.Polygon
      } else if (type === 'Box') {
        this._drawForm = this.Box
      }
      if (type === 'Point') {
        this._snap = new Snap({ source: CameraSource })
      } else {
        this._snap = new Snap({ source: FenceSource })
      }
      _iMap.addInteraction(this._snap)
      _iMap.addInteraction(this._drawForm)
    },

    fenceDraw_setEvents: function(type) {
      const self = this
      //* *****************绘制电子围栏tooltip开始******************//
      let sketch
      const pointerMoveHandler = function(evt) {
        if (evt.dragging) {
          return
        }
        let Msg = '点击开始绘制围栏'
        if (sketch) {
          const type = sketch.getGeometry().getType()
          // console.log(type);
          switch (type) {
            case 'Polygon':
              Msg = '点击下一个点，或双击完成绘制'
              break
            case 'Circle':
              Msg = '点击外圆任意一点完成绘制'
              break
            case 'LineString':
              Msg = '点击下一个点LineString'
              break
            case 'Point':
              Msg = '点击绘制点'
              break
            default:
              Msg = ''
          }
        } else {
          Msg = '[' + _TransMetric(evt.coordinate, 4) + ']'
        }
        // Tooltip.setPosition(evt.coordinate);
        $(TooltipElement).html(Msg).removeClass('hidden')
      }
      _iMap.on('pointermove', pointerMoveHandler)
      $(_iMap.getViewport()).on('mouseout', function() {
        $(TooltipElement).addClass('hidden')
      })

      /**
       * measureTooltip刷新事件
       */
      let listener
      const listenerCoord = function(sketch) {
        listener = sketch.getGeometry().on('change', function(evt) {
          const geom = evt.target
          let tooltipCoord = sketch.getCenter
          let output
          if (geom instanceof Polygon) {
            output = formatArea(geom)
            tooltipCoord = geom.getInteriorPoint().getCoordinates()
          } else if (geom instanceof LineString) {
            output = formatLength(geom)
            tooltipCoord = geom.getLastCoordinate()
          }
          if (geom instanceof Circle) {
            output = formatCircle(geom)
            tooltipCoord = geom.getCenter()
          }
          $(measureTooltipElement).html(output)
          // console.log("output:" + output + "____" + "innerText:" + $(measureTooltipElement).html());
          measureTooltip.setPosition(tooltipCoord)
        })
      }

      /**
       * 开始绘制事件侦听
       */
      let newFence = null
      // let bLock = false;

      this[type].on(
        'drawstart',
        function(evt) {
          sketch = evt.feature
          const tooltipCoord = evt.coordinate
          listenerCoord(sketch, tooltipCoord) // 围栏监听
        },
        this
      )

      /**
       * 结束绘制事件侦听
       */
      this[type].on(
        'drawend',
        function(evt) {
          listenerCoord(evt.feature) // 围栏监听
          newFence = evt.feature
          const coors = newFence.getGeometry().getCoordinates()
          // console.log(coors);
          if (newFence.getGeometry().getType() == 'Point') {
            console.log('摄像头')
            self.editVisible = true
            self.fenceEditVisible = false
            self.editEnable = true
            self.form = {}
            self.coors = '[' + _TransMetric(coors, 4).toString() + ']'
            // console.log(self.coors)
          } else {
            console.log('围栏')
            self.editVisible = false
            self.fenceEditVisible = true
            self.fenceForm = {}
            self.coors = '[' + _TransMetric(coors, 4).toString() + ']'
            // console.log(self.coors)
          }
          // FenceSource.addFeature(newFence);

          $(TooltipElement).addClass('hidden') // 隐藏工具条
          sketch = null
        },
        this
      )

      /**
       * format length output
       * @param {ol.geom.LineString} line
       * @return {string}
       */
      const formatLength = function(line) {
        const length = Math.round(line.getLength() * 100) / 100 / _dPR
        let output
        if (length > 100) {
          output = Math.round((length / 1000) * 100) / 100 + ' ' + 'km'
        } else {
          output = Math.round(length * 100) / 100 + ' ' + 'm'
        }
        return output
      }
      /**
       * format length output
       * @param {ol.geom.Polygon} polygon
       * @return {string}
       */
      const formatArea = function(polygon) {
        const area = polygon.getArea() / _dPR / _dPR
        let output
        if (area > 10000) {
          output =
            Math.round((area / 1000000) * 100) / 100 + ' ' + 'km<sup>2</sup>'
        } else {
          output = Math.round(area * 100) / 100 + ' ' + 'm<sup>2</sup>'
        }
        return output
      }
      /**
       * format length output
       * @param {ol.geom.Circle} Circle
       * @return {string}
       */
      const formatCircle = function(Circle) {
        const area = (2 * Math.PI * Circle.getRadius()) / _dPR / _dPR
        let output
        if (area > 10000) {
          output =
            Math.round((area / 1000000) * 100) / 100 + ' ' + 'km<sup>2</sup>'
        } else {
          output = Math.round(area * 100) / 100 + ' ' + 'm<sup>2</sup>'
        }
        return output
      }
      //* *****************绘制电子围栏tooltip结束******************//
    },

    fenceDraw_getActive: function() {
      return this.activeType ? this[this.activeType].getActive() : false
    },
    fenceDraw_setActive: function(active, type) {
      if (active) {
        this.activeType && this[this.activeType].setActive(false, type)
        this[type].setActive(true, type)
        this.fenceDraw_setEvents(type)
        this.activeType = type
      } else {
        this.activeType && this[this.activeType].setActive(false, type)
        this.activeType = null
      }
    },
    fenceDraw_Destroy: function() {
      if (this._snap != null && this._drawForm != null) {
        this.fenceDraw_setActive(false, this._tempval)
        _iMap.removeInteraction(this._snap)
        _iMap.removeInteraction(this._drawForm)
        console.log('销毁FenceDrawd事件')
      }
    },

    /**
     * 修改围栏开始
     */

    fenceModify_init: function() {
      this._select = new Select()
      _iMap.addInteraction(this._select)
      // this.fenceModify_setEvents();
      // this.fenceModify_Modify();
    },
    fenceModify_Modify: function() {
      const _selectedFeatures = this._select.getFeatures()
      const self = this
      this._modify = new Modify({
        features: _selectedFeatures,
        insertVertexCondition: function() {
          // prevent new vertices to be added to the polygons
          return !this.features_.getArray().every(function(feature) {
            return feature
              .getGeometry()
              .getType()
              .match(/Polygon/)
          })
        }
      })
      _iMap.addInteraction(this._modify)
      /**
       * 结束修改事件侦听
       */
      this._modify.on(
        'modifyend',
        function(evt) {
          _selectedFeatures.forEach(function(e) {
            const coordinate = e.getGeometry().getCoordinates()
            console.log(e.getGeometry().getType())
            const coor = '[' + _TransMetric(coordinate, 4) + ']'
            const param = {
              idx: e.get('id'),
              posGroupArray: eval(coor)
            }
          })
        },
        this
      )
    },
    fenceModify_Drag: function(_selectedFeatures) {
      this._translate = new Translate({
        features: _selectedFeatures
      })
      _iMap.addInteraction(this._translate)
    },
    fenceModify_Delete: function() {
      const _selectedFeatures = this._select.getFeatures()
      const self = this
      // console.log(_selectedFeatures);
      _selectedFeatures.forEach(function(e) {
        // console.log("id:" + e.get('id'));
        self.selectFeature = e
        self.idx = e.get('id')
        self.delFenceVisible = true
      })
      // _selectedFeatures.forEach(_selectedFeatures.remove, _selectedFeatures);
      _selectedFeatures.clear()
    },

    fenceModify_getSelectFeatures: function() {
      return this._select.getFeatures()
    },

    fenceModify_setEvents: function() {
      const self = this
      const _selectedFeatures = this._select.getFeatures()
      this._select.on('change:active', function() {
        _selectedFeatures.forEach(_selectedFeatures.remove, _selectedFeatures)
      })

      this.fenceModify_Drag(_selectedFeatures) // 增加拖拽
      /**
       * 结束拖拽事件侦听
       */
      this._translate.on('translateend', function(evt) {
        _selectedFeatures.forEach(function(e) {
          const coordinate = e.getGeometry().getCoordinates()
          const coor = '[' + _TransMetric(coordinate, 4) + ']'
          const param = {
            idx: e.get('id'),
            posGroupArray: eval(coor)
          }
          addFence(param).then((res) => {
            const RES = this.responseUse(res, true)
            if (RES) {
            }
          })
        })
      })
    },
    fenceModify_setActive: function(active) {
      this._select.setActive(active)
      this._modify.setActive(active)
    },
    fenceModify_Destroy: function() {
      if (this._select != null && this._modify != null) {
        // this.setActive(false);
        _iMap.removeInteraction(this._select)
        _iMap.removeInteraction(this._translate)
        _iMap.removeInteraction(this._modify)
      }
    },
    // 弹出相片
    testPhoto: function(index, row) {
      getSingleCameraPhoto(row.idx)
        .then((res) => {
          // let RES = this.responseUse(res);
          // let format = new GeoJSON();
          // let cameraFeatures = format.readFeatures(RES);
          // console.log('解析之后的GeoJson数据：', cameraFeatures);
          // cameraFeatures.forEach(function (f) {
          //   let tempcoord = f.getGeometry().getCoordinates();
          //   let pos = _TransPixel(tempcoord);
          //   _PopupVideo(f, pos);
          // })
          // console.log(res)
          // console.log(res)
          if (typeof res === 'undefined') {
            this.v_MyMessage(this.$t('Notice.moniterOut'), 'warning')
          } else {
            this.show8 = true
            this.imageURl = 'http://' + window.g.IP + ':8002/' + res.msg
          }
          // this.imageURl = "http://192.168.0.80:8002//files/IMAGE/2020.7/bcfbc92635ce4f70945eec81c6873e25.jpg";
        })
        .catch((error) => {})
    },
    stateFormat(row, column) {
      if (row.cameraVendor === '0') {
        return '海康威视'
      } else if (row.cameraVendor === '1') {
        return '大华'
      } else if (row.cameraVendor === '2') {
        return '华为'
      } else if (row.cameraVendor === '3') {
        return 'TP-LINK'
      }
    }
  }
}
</script>
<style scoped>
#body {
  width: 100%;
  height: 100%;
  overflow: hidden;
}
.handle-box {
  background-color: #939e89;
  padding: 10px;
  margin-bottom: 10px;
  min-width: 950px;
}
.buttonRt {
  float: right;
}
.clear {
  clear: both;
}
.areaSelect {
  position: absolute;
  margin-top: 30px;
  left: 20px;
  width: 200px;
  /*float: right;*/
  z-index: 2000;
}

span {
  margin-left: 0px;
  font-size: 13px;
}
.datalist {
  width: 100%;
  min-width: 1150px;
}

.fenceTable {
  width: 300px;
  background-color: #fff;
  position: fixed;
  z-index: 100;
  top: 325px;
  right: 0;
}
.vue-treeselect {
  width: 200px;
  display: inline-block;
  height: 32px;
  top: 8px;
}

.content2 >>> .vue-treeselect__control {
  height: 32px;
  box-sizing: border-box;
}
.content2 >>> .vue-treeselect__placeholder {
  font-size: 12px;
}
.content2 >>> .vue-treeselect__menu {
  font-size: 12px;
}
.content2 >>> .vue-treeselect__single-value {
  font-size: 12px;
}
.content1 {
  width: 100%;
  overflow: hidden;
}

#panel {
  width: 270px;
  height: 200px;

  position: fixed;
  z-index: 100;
  /*right: 0;*/
  transition: right 1s;
  -moz-transition: right 1s; /* Firefox 4 */
  -webkit-transition: right 1s; /* Safari 和 Chrome */
  -o-transition: right 1s; /* Opera */
}
#panel .isShow {
  width: 30px;
  height: 100%;
  float: left;
  margin-bottom: 5px;
}
#panel .isShow span {
  display: block;
  width: 30px;
  height: 30px;
  margin: 0 auto;
  position: absolute;
  /*top: 50%;*/
  /*margin-top: -24px;*/
  margin-left: 2px;
  background-color: #00d1b2;
  font-size: 24px;
  color: #fff;
  cursor: pointer;
}
#panel .content2 {
  background-color: #fff;
  padding: 10px;
  float: right;
  width: 248px;
  height: 100%;
  border: #d0c4cc 1px solid;
}
.crumbs {
  height: 36px;
}
.changeBtn {
  width: 235px;
  padding: 5px 15px;
  z-index: 9999;
}
.changeBtn >>> i {
  font-size: 16px;
}
.titleHandle {
  width: 100%;
  margin-bottom: 16px;
}
.titleHandle > div {
  display: inline-block;
  margin-right: 10px;
}
.titleHandle > div + div {
  margin-left: 10px;
}

/* #mapbox >>> .ol-unselectable {
  bottom: 30px !important;
} */
</style>

